// import AsyncStorage from '@react-native-async-storage/async-storage';
import store from 'app/store';
import axios, {AxiosResponse, AxiosError} from 'axios';
import {ToastAndroid} from 'react-native';
import {navigate} from 'utils/naviRef';
const request = axios.create({
  timeout: 6000,
  method: 'post',
  // baseURL: 'https://192.168.3.112:8089',
  baseURL: 'https://lingjlkdyt.abuav.com.cn:8098',
});
request.interceptors.request.use(
  async function (config) {
    // 在发送请求之前做些什么
    const {needToken = true} = config;
    if (needToken) {
      config.headers.token = store.getState().user.token;
    }
    return config;
  },
  function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
  },
);
type dataType<T = any> = {
  msg: string;
  code: number;
  data: T;
};

// 添加响应拦截器
request.interceptors.response.use(
  function ({data}: AxiosResponse<dataType>) {
    // 对响应数据做点什么
    const {code, msg, data: responseData} = data;
    if ([0, 200].includes(code)) {
      return responseData;
    } else {
      if (code == 401) {
        navigate('login', {});
        return ToastAndroid.showWithGravity(
          '登录状态已过期',
          2000,
          ToastAndroid.TOP,
        );
      }
      ToastAndroid.showWithGravity(msg, 2000, ToastAndroid.TOP);
      return Promise.reject(new Error(msg));
    }
  },
  function (error: AxiosError<any>) {
    // 对响应错误做点什么
    return ToastAndroid.showWithGravity(
      error.response?.data.msg ?? error.message,
      2000,
      ToastAndroid.TOP,
    );
  },
);
export default request;
